package com.self.chan.tio;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.self.chan.model.ResponseEntity;
import com.self.common.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.server.handler.IWsMsgHandler;

/**
 * @version v1.0
 * @ClassName: WebSocketMessageHandler
 * @Description:
 * @Author: Mac
 */
@Component
@Slf4j
public class WebSocketMessageHandler implements IWsMsgHandler {


    /**
     * @Title: 握手
     * @Description:
     * @Param [httpRequest, httpResponse, channelContext]
     * @Return org.tio.http.common.HttpResponse
     * @Author Mac
     * @Throws
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        String clientIp = httpRequest.getClientIp();
        log.info("收到来自ip:{},ws握手包:{}", clientIp, httpRequest.toString());
        return httpResponse;
    }

    /**
     * @Title: 握手后回调
     * @Description:
     * @Param [httpRequest, httpResponse, channelContext]
     * @Return org.tio.http.common.HttpResponse
     * @Author Mac
     * @Throws
     */
    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

    }

    /**
     * @Title: 有字节消息回调
     * @Description:
     * @Param [httpRequest, httpResponse, channelContext]
     * @Return org.tio.http.common.HttpResponse
     * @Author Mac
     * @Throws
     */
    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        return null;
    }

    /**
     * @Title: 客户端关闭回调
     * @Description:
     * @Param [httpRequest, httpResponse, channelContext]
     * @Return org.tio.http.common.HttpResponse
     * @Author Mac
     * @Throws
     */
    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        //Tio.remove(channelContext,"客户关闭");
        return null;
    }

    /**
     * @Title: 处理消息回调
     * @Description:
     * @Param [httpRequest, httpResponse, channelContext]
     * @Return org.tio.http.common.HttpResponse
     * @Author Mac
     * @Throws
     */
    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
        if ("ping".equalsIgnoreCase(text)){
            return "pong";
        }
        // 订阅消息 ch 为订阅的频道 id 为订阅唯一标识
        JSONObject payload = JSONObject.parseObject(text);
        String sub = payload.getString("sub");
        String req = payload.getString("req");
        String cancel = payload.getString("cancel");
        String id = payload.getString("id");

        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setSubbed(sub).setStatus("ok");
        //如果用户的authorization 数据
        String authorization = payload.getString("authorization");
        if (StringUtils.hasText(authorization) && authorization.startsWith(CommonConstants.TOKEN_PROFIX)){
            JSONObject jsonObject = JSON.parseObject(JwtHelper.decode(authorization.replaceAll(CommonConstants.TOKEN_PROFIX, "")).getClaims());
            String userId = jsonObject.getString("user_name");
            Tio.bindUser(channelContext,userId);
            return responseEntity.setId(userId).build();
        }else if (StringUtils.hasText(sub)){
            Tio.bindGroup(channelContext,sub);
            return responseEntity.build();
        }else if (StringUtils.hasText(cancel)){
            Tio.unbindGroup(cancel,channelContext);
            return responseEntity.setCanceled(cancel).build();
        }
        return null;
    }
}
